#include "mysql_op.h"

int getUsrId(char *username)
{
    int usrid = -1;
    OPEN_MYSQL(myconnect);
    char *query = "SELECT id FROM user WHERE username = ";
    char sqlarray[1024] = {0};
    sprintf(sqlarray, "%s\"%s\"", query, username);
    printf("sqlarray = %s\n", sqlarray);
    mysql_query(&myconnect, sqlarray);
    MYSQL_RES *result = mysql_store_result(&myconnect);
    MYSQL_ROW row = mysql_fetch_row(result);
    usrid = atoi(row[0]);
    mysql_free_result(result);
    CLOSE_MYSQL(myconnect);
    return usrid;
}

int InsertVirtualFile(MYSQL *mysql, char *value)
{
    char sql[1024] = {0};
    snprintf(sql, 1024, "INSERT INTO virtualfile(parent_id,filename,owner_id,md5,filesize,type) values (%s)", value);
    int ret = mysql_query(mysql, sql);
    if (ret != 0)
    {
        printf("插入表数据失败！失败原因：%s\n",
               mysql_error(mysql));
        return -1;
    }
    return 0;
}

char* GetPwd(MYSQL* mysql,int userid)
{
    char query[1024] = {0};
    sprintf(query,"SELECT pwd FROM user WHERE id = %d",userid);
    mysql_query(mysql,query);
    MYSQL_RES* result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    return row[0];
}

int ExitFile(MYSQL* mysql,char* filename,int userid,int pid)
{
    //0有，-1无
    char query[1024] = {0};
    sprintf(query,"SELECT id from virtualfile WHERE filename = \"%s\" and owner_id = %d and parent_id = %d",filename,userid,pid);
    printf("文件存在判断语句:%s\n",query);
    mysql_query(mysql,query);
    MYSQL_RES* result = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    if(row != NULL)
    {
        printf("row[0]:%s\n",row[0]);
        return 0;
    }
    return -1;
}

char* Getmd5(MYSQL mysql,int userid,char* filename)
{
    char* pwd = GetPwd(&mysql,userid);
    int pid = findID(mysql,pwd);
    char query[1024] = {0};
    sprintf(query,"SELECT md5 FROM virtualfile WHERE parent_id = %d and owner_id = %d and filename = \"%s\"",pid,userid,filename);
    mysql_query(&mysql,query);
    MYSQL_RES* result = mysql_store_result(&mysql);
    MYSQL_ROW row = mysql_fetch_row(result);
    return row[0];
}